package sample;

import java.awt.Color;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;

import robocode.Robot;
import robocode.ScannedRobotEvent;
import utfpr.si.connection.Client;
import utfpr.si.interfaces.IntServidor;

public class RoboA extends Robot {
	private Client cli;
	private IntServidor refServer;
	private boolean refem = false;
	private boolean refemVisto = false;

	public RoboA(){
        System.out.println("iniciou o Robo Scanner");
        try {
            cli = new Client(1313,"localhost");
            cli.initClient();
            refServer = cli.getRefServer();
        } catch (RemoteException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
	}

	@Override
	public void run() {
		setBodyColor(Color.BLUE);
		setScanColor(Color.BLUE);
		String action = "";
		double h = 0, t = 0;
		while(true){
			try {
				action = refServer.getAction(getX(), getY());
				
				if( action.split(" ")[0].equals("AHEAD") && !refem ){
					h = getHeading();
					t = Double.parseDouble(action.split(" ")[2]);
					if( h < 180 ) turnLeft(h+(t-90.0));
					else turnRight(360.0-h-(t-90.0));
					ahead(Double.parseDouble(action.split(" ")[1]));
				}else if( ! refem ){
					turnRadarLeft(360);
				}else{
					ahead(20);
				}
				//Thread.sleep(150);
			} catch (RemoteException e) {
				e.printStackTrace();
			} 
			/*catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/
		}
	}

	@Override
	public void onScannedRobot(ScannedRobotEvent event) {
		if( !event.getName().equals("sample.RoboScannerA")){
			if( event.getDistance() < 80 ){
				refem = true;
				turnRight( event.getBearing() + 180 );
				ahead( 30 );
				turnRadarLeft(360.0);
			}else if ( !refemVisto &&  !event.getName().equals("sample.RoboScannerA") ){
				double b = event.getBearing();
				if( b < 0 ) b = Math.abs(b);
				else b = 360.0 - b;
				double targetX = this.getX()+event.getDistance()*Math.cos(Math.toRadians(b));
				double targetY = this.getY()+event.getDistance()*Math.sin(Math.toRadians(b));
				System.out.println(event.getName()+" ("+targetX+","+targetY+")");
				try {
					synchronized (event) {
						refServer.updateTable(event.getName(), targetX, targetY);
					}
				} catch (RemoteException e) {
					e.printStackTrace();
				}
				refemVisto = true;
			}
		}
	}
	

	
}
